<template>
  <view>
    <!-- 商品列表 -->
    <view class="goods-list">
      <view v-for="(item, index) in goodList" :key="index" @click="goGoodsDetail(item)">
        <!-- 列表项组件-->
        <my-goods :goods="item"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        searchQuery: {
          query: '', // 查询关键词
          cid: '', // 分类ID
          pagenum: 1, // 页码值
          pagesize: 10 // 每页数据条数
        },
        goodList: [], // 商品数据列表
        total: 0, // 总数据
        isLoading: false // 节流阀
      }
    },
    onLoad(options) {
      // 页面传参数据
      this.searchQuery.query = options.query || ''
      this.searchQuery.cid = options.cid || ''
      // 获取商品数据列表
      this.getGoodList()
    },
    methods: {
      async getGoodList(cb) {
        // 节流
        this.isLoading = true
        // 发送网络请求
        const {
          data: res
        } = await uni.$http.get('/goods/search', this.searchQuery)
        // 判断是否回调
        cb && cb()
        // 判断
        if (res.meta.status !== 200) return uni.$showMsg()
        // 成功赋值
        this.goodList = [...this.goodList, ...res.message.goods]
        this.total = res.message.total
        this.isLoading = false
      },
      // 点击跳转详情页
      goGoodsDetail(val) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + val.goods_id
        })
      }
    },
    onReachBottom() {
      if (this.searchQuery.pagenum * this.searchQuery.pagesize >= this.total) return uni.$showMsg('数据加载完毕')
      // 节流
      if (this.isLoading) return
      // 切换下一页
      this.searchQuery.pagenum++
      // 发送数据请求
      this.getGoodList()
    },
    onPullDownRefresh() {
      // 制空关键数据
      this.searchQuery.pagenum = 1
      this.total = 0
      this.isLoading = false
      this.goodList = []
      // 回调函数
      this.getGoodList(() => uni.stopPullDownRefresh())
    }
  }
</script>

<style lang="scss">

</style>
